package com.hooker.adapter

import android.content.Context
import android.content.Intent
import android.os.Parcelable
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.hooker.bean.TypeInfo
import com.hooker.common.HookHelper
import com.hooker.penetration.TypeFilterActivity
import com.hooker.settings.Setting
import com.hooker.settings.SettingHelper
import com.hooker.util.Constants
import com.sdk.debug.mode.DebugAgent
import com.sdk.hooker.penetration.R
import com.top.web.hooker.AppSelectActivity
import com.top.web.hooker.common.HookerIntent
import java.util.regex.Pattern

/**
 * 一共有哪些type  file、network
 */
class TypeListAdapter : RecyclerView.Adapter<TypeListAdapter.TypeHolder> {

    var context: Context? = null
    var list: MutableList<TypeInfo> = mutableListOf()
    var listView: RecyclerView? = null
    var packageName: String? = null
    var mapProcess: MutableMap<String, String?> = mutableMapOf()

    constructor(context: Context?, list: MutableList<TypeInfo>, view: RecyclerView, name: String?) {
        this.context = context
        this.list.addAll(list)
        this.listView = view
        this.packageName = name
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TypeHolder {
        var view: View = View.inflate(context, R.layout.layout_type, null)
        view.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        return TypeHolder(view)
    }

    override fun getItemViewType(position: Int): Int {
        if ("1".equals(list.get(position).type)) {
            return 1;
        }
        return 0;
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: TypeHolder, position: Int) {
        var info = list?.get(position)

        holder?.typeName?.text = info?.name

        var state = Setting.get(context, SettingHelper.getBuildInfo(packageName, info.id))

        when (state) {
            "1" -> {
                holder?.checkBox?.isChecked = true
                holder?.settingType?.isEnabled = true
            }

            "0" -> {
                holder?.checkBox?.isChecked = false
                holder?.settingType?.isEnabled = false
            }

            null -> {
                holder?.checkBox?.isChecked = false
                holder?.settingType?.isEnabled = false
            }
        }

        if ("1".equals(state)) {
            bindLayoutBottom(holder, info, true);
        } else {
            bindLayoutBottom(holder, info, false);
        }

        holder.checkBox.tag = info
        holder.checkBox.setOnCheckedChangeListener { view, isChecked ->
            var item = view.tag as TypeInfo
            when (isChecked) {
                true -> {
                    Setting.put(context, SettingHelper.getBuildInfo(packageName, item.id), "1")
                    holder?.settingType?.isEnabled = true
                }
                false -> {
                    Setting.put(context, SettingHelper.getBuildInfo(packageName, item.id), "0")
                    holder?.settingType?.isEnabled = false
                }
            }
            bindLayoutBottom(holder, item, isChecked)
        }

        holder.settingType?.setTag(R.id.position, position)
        holder.settingType?.tag = info

        holder.settingType?.setOnClickListener { view ->
            var info = view.tag as TypeInfo
            if (Constants.HookType.HOOKER_INJECT.getId().equals(info.id)) {
                var intent = Intent(context, AppSelectActivity::class.java)
                intent.putExtra(AppSelectActivity.FROM, HookerIntent.FROM_INJECT)
                intent.putExtra(AppSelectActivity.PACKAGE, packageName)
                context?.startActivity(intent)
            } else {
                var intent = Intent(context, TypeFilterActivity::class.java)
                intent.putExtra("extra", info as Parcelable)
                intent.putExtra("package", packageName)
                context?.startActivity(intent)
            }
        }
    }

    /**
     * 绑定服务
     */
    private fun bindLayoutBottom(holder: TypeHolder, info: TypeInfo, checked: Boolean) {
        //只有注入和debug才生效
        var checkTemp = false
        if (checked &&
            (Constants.HookType.HOOKER_INJECT.getId()
                .equals(info?.id) || Constants.HookType.HOOKER_DEBUG.getId().equals(info?.id))
        ) {
            checkTemp = true
        }

        when (checkTemp) {
            true -> {
                showBottomViewInfo(holder, info)
            }
            false -> {
                holder.layoutBottom.visibility = View.GONE
            }
        }
    }

    private fun showBottomViewInfo(holder: TypeHolder, info: TypeInfo) {
        holder.layoutBottom.visibility = View.VISIBLE

        val pTag by lazy {
            when (info.id) {
                Constants.HookType.HOOKER_DEBUG.getId() -> {
                    holder.moreInfo.setHint(R.string.type_debug_address)
                    holder.completeType.setText(R.string.start_type)
                    SettingHelper.getBuildInfo(packageName, info.id, "debug");
                }
                Constants.HookType.HOOKER_INJECT.getId() -> {
                    holder.moreInfo.setHint(R.string.type_hook_process)
                    holder.completeType.setText(R.string.complete_type)
                    SettingHelper.getBuildInfo(packageName, info.id, "process");
                }
                else -> ""
            }
        }

        if (mapProcess.get(pTag) == null) {
            mapProcess.put(pTag, Setting.get(context, pTag))
        }

        mapProcess[pTag].let {
            holder.moreInfo.setText(it);
        }

        holder.completeType.tag = info
        holder.completeType.setOnClickListener { l ->
            var item = l.tag as TypeInfo
            when (item.id) {
                Constants.HookType.HOOKER_DEBUG.getId() -> {
                    try {
                        var rule = "([0-9]{1,3}.){3}[0-9]{3}:[0-9]{3,5}"
                        var pattern: Pattern = Pattern.compile(rule)
                        if (pattern.matcher(holder.moreInfo.text.toString()).matches()) {
                            Setting.put(
                                context,
                                pTag,
                                holder.moreInfo.text.toString()
                            )
                            mapProcess[pTag] = holder.moreInfo.text.toString()

                            var address_port = holder.moreInfo.text.toString().split(":")
                            var address = address_port[0]
                            var port = address_port[1].toInt();
                            DebugAgent.start(context, address, port)
                            HookHelper.submitUiThread {
                                Toast.makeText(
                                    context?.applicationContext,
                                    "启动成功",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        } else {
                            HookHelper.submitUiThread {
                                Toast.makeText(
                                    context?.applicationContext,
                                    "输入不符合规则:" + rule,
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    } catch (e: Exception) {

                    }
                }
                Constants.HookType.HOOKER_INJECT.getId() -> {
                    Setting.put(
                        context,
                        pTag,
                        holder.moreInfo.text.toString()
                    )
                    mapProcess[pTag] = holder.moreInfo.text.toString()
                    HookHelper.submitUiThread {
                        Toast.makeText(context?.applicationContext, "设置成功", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
            }
        }
    }

    class TypeHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        companion object

        var typeName: TextView? = null
        var settingType: TextView? = null
        var checkBox: CheckBox
        var layoutBottom: LinearLayout
        var moreInfo: EditText
        var completeType: TextView

        init {
            typeName = itemView.findViewById(R.id.tv_type_name)
            settingType = itemView.findViewById(R.id.tv_setting_type)
            checkBox = itemView.findViewById(R.id.checkbox_id)
            layoutBottom = itemView.findViewById(R.id.layout_type_bottom)
            moreInfo = itemView.findViewById(R.id.type_more_info)
            completeType = itemView.findViewById(R.id.tv_type_complete)
        }
    }
}